﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using Itop.YHPC.Model;
using System.Collections.Generic;
using System.Text;
using Itop.YHPC.controller;

namespace Itop.YHPC.reward
{
    public partial class Export1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string id = Request.QueryString["id"];
            string sheetname = Request.QueryString["sheetname"];
            string type = Request.QueryString["type"];
            if (id == null) {
                System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream, Encoding.UTF8);
                id = Server.UrlDecode( sr.ReadToEnd());//字符串格式id=id1,id2,
                sr.Close();
                if (id.Length > 3)
                    id = id.Substring(3);
                
            }
            //int yhNo = GetTextNum(text);
            
            if (id != "")
            {
                string[] arr = id.Split(",".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
                StringBuilder where = new StringBuilder();
                where.Append(" where 1<>1 ");
                foreach (string str in arr)
                    where.Append(" or id='"+str+"'");
                IList<yhpcMain> list = workflowController.GetMainList(where.ToString());
                FillData(list, sheetname, type, 0);
                    
            }
        }
        string khformat = "事故隐患内容:{0}\n整改措施:{1}\n治理期限:自{2}至{3}\n治理完成情况:{4}\n验收日期:{5}";
        public void FillData(IList<yhpcMain> list,string sheetname,string type,int no)
        {
            int yhbh = no;
            string pathdic = "";
            if (Request.Path.Contains("yhpc")) pathdic = @"\yhpc";
            FileStream fs = new FileStream(Server.MapPath(pathdic+@"\search\Template\"+type+".xls"), FileMode.Open, FileAccess.Read);
            HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);
            HSSFSheet sheet=null;
            SortedDictionary<string,string> a_ht;
            if(type=="reward")
                a_ht= GetAMapping();
            else
                a_ht = GetBMapping();
            HSSFRow dataRow;
            int num = 0;
            int rownum = 0;
            foreach (yhpcMain main in list)
            {
                
                rownum++;
                if (rownum == 1) {
                    num++;
                    sheet = templateWorkbook.CloneSheet(0);
                    templateWorkbook.SetSheetName(0, "aa");
                }
                
                dataRow = sheet.GetRow(rownum+1);
                dataRow.GetCell(0).SetCellValue(rownum+26*(num-1));
                if (rownum == 26)
                    rownum = 0;

                for (int i = 0; i < main.GetType().GetProperties().Length; i++)
                {
                    string property = main.GetType().GetProperties()[i].Name;
                    if (a_ht.ContainsKey(property))
                    {
                        string cellvalue = main.GetType().GetProperty(property).GetValue(main, null).ToString();
                        if (main.GetType().GetProperties()[i].PropertyType.FullName == "System.DateTime")
                        { 
                            cellvalue = Convert.ToDateTime(cellvalue).ToString("yyyy-MM-dd");
                            if (cellvalue.StartsWith("1900-01-01"))
                                cellvalue = "";
                        }
                        if (property == "sfzykz")
                            cellvalue = cellvalue == "on" ? "是" : "否";
                        dataRow.GetCell(GetColumn(a_ht[property].ToString())).SetCellValue(cellvalue);
                    }
                }
                if (type == "check") {
                    string kh = string.Format(khformat, main.fxyhnr, main.zgcs, main.zlrq1.ToString("yyyy-MM-dd"), main.zlrq2.ToString("yyyy-MM-dd"), main.zlwcqc, main.ysrq.ToString("yyyy-MM-dd"));
                    dataRow.GetCell(3).SetCellValue(kh);
                }

                string temp = sheetname;
                
                templateWorkbook.SetSheetName(num, temp + num.ToString());

            }
            templateWorkbook.RemoveSheetAt(0);
            string filename = sheetname+"档案表"+type+DateTime.Now.ToString("yyyy-MM-dd")+".xls";
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
            Response.Clear();
            Response.BinaryWrite(WriteToStream(templateWorkbook).GetBuffer());
            Response.End();
        }

        MemoryStream WriteToStream(HSSFWorkbook templateWorkbook)
        {
            MemoryStream file = new MemoryStream();
            templateWorkbook.Write(file);
            return file;
        }

        public int GetRow(string str)
        {
            return int.Parse(str.Split('|')[0])-1;
        }

        public int GetColumn(string str)
        {
            return int.Parse(str.Split('|')[1])-1;
        }

        public int GetTextNum(string text)
        {
            if (string.IsNullOrEmpty(text))
                return 0;
            string rst=text;
            for (int i = 0; i < text.Length; i++)
            {
                if (text[i] != '0')
                { rst = text.Substring(i); break; }
            }
            return int.Parse(rst);
        }

        public SortedDictionary<string, string> GetAMapping()
        {
            SortedDictionary<string, string> ht = new SortedDictionary<string, string>();
            
            ht["yhfxr"]="2|3";
            ht["fxrdw"]="2|2";
            ht["fxyhnr"]="2|4";
            ht["fxrgh"]="2|5";
            ht["jlje"]="2|6";
            ht["sfzykz"]="2|7";

            return ht;
        }

        public SortedDictionary<string, string> GetBMapping()
        {
            SortedDictionary<string, string> ht = new SortedDictionary<string, string>();
            ht["zlr"] = "2|3";
            ht["zldw"] = "2|2";
            ht["jlje"] = "2|5";

            return ht;
        }
    }
}
